'use strict';

angular.module('SystemManage').controller('UserController', ['$rootScope', '$scope', '$cookies', '$stateParams', '$modal', 'User', 'BaseModule', 'BaseFunction', 'BaseEnum', 'EntityService', '$location', 'Authentication', 'ImageCompress', 'usbPort',
    function($rootScope, $scope, $cookies, $stateParams, $modal, User, BaseModule, BaseFunction, BaseEnum, EntityService, $location, Authentication, ImageCompress, usbPort) {
        //$scope.authentication = Authentication;
        $scope.data = {
            myCroppedImage: 'users/img/default.png',
            url: 'api/fileUpload',
            Authorization: 'Bearer ' + $cookies.get('U9USS'),
            uploadType: 'avatar',
            filePath: './public/users/img/'
        };
        $scope.myImage = '';
        var myModal = $modal({
            scope: $scope,
            placement: 'center',
            show: false,
            animation: 'am-fade-and-scale',
            templateUrl: 'modules/User/client/views/avatar.client.view.html',
            backdrop: false
        });
        $scope.init = function() {
            usbPort.start();
        }
        $scope.init();

        $scope.$on('usbPort.input', function(e, inputStr) {
            $scope.Module.User.FocusedRecord.UniqueID = inputStr;
            $scope.$apply();
        });

        $scope.$on('$destroy', function() {
            usbPort.stop();
        });

        $scope.btnSave = function() {
            if ($scope.Module.User.FocusedRecord.Code === undefined ||
                $scope.Module.User.FocusedRecord.Code.trim() === "") {
                BaseFunction.alert("用户名为空！", "保存错误");
                return;
            }
            if ($scope.Module.User.FocusedRecord.Name === undefined ||
                $scope.Module.User.FocusedRecord.Name.trim() === "") {
                BaseFunction.alert("名称不能为空！", "保存错误");
                return;
            }
            if ($scope.Module.User.FocusedRecord.Email != undefined &&
                $scope.Module.User.FocusedRecord.Email != null && 
                $scope.Module.User.FocusedRecord.Email != "" ){
                var email = $scope.Module.User.FocusedRecord.Email.replace(/ /g, "");
                var singCount = email.match(/@/g);
                if(singCount == null || singCount.length != 1 || email.substring(0,1) == "@" || email.substring(email.length - 1, email.length) == "@"){
                    BaseFunction.alert("邮箱格式不正确！", "保存提示");
                    return;
                }                
            }

            var roles = [];
            for (var i = 0; i < $scope.Module._Role.Records.length; i++) {
                if ($scope.Module._Role.Records[i].Role === undefined ||
                    $scope.Module._Role.Records[i].Role === null) {
                    BaseFunction.alert("系统角色不能为空！", "保存错误");
                    return;
                }
                for (var j = 0; j < roles.length; j++) {
                    if (roles[j]._id === $scope.Module._Role.Records[i].Role._id) {
                        BaseFunction.alert("系统角色不能重复！", "保存错误");
                        return;
                    }
                }
                roles.push($scope.Module._Role.Records[i].Role);
            }

            $scope.Module.User.FocusedRecord.Roles = roles;
            if ($scope.Module.User.FocusedRecord.RowStatus === BaseEnum.RowStatus.UnChange.Value) {
                $scope.Module.User.FocusedRecord.RowStatus = BaseEnum.RowStatus.Modify.Value;
            }

            if ($scope.data.myCroppedImage.indexOf('base64') < 0) {
                $scope.Module.User.FocusedRecord.Image = ($scope.Module.User.FocusedRecord.Image ? $scope.Module.User.FocusedRecord.Image : $scope.data.myCroppedImage);
                $scope.Module.User.save();
            }
            else {
                //author:jiadx先上传头像，在保存其他内容
                var form = new FormData();
                form.append('file', convertBase64UrlToBlob($scope.data.myCroppedImage));
                form.append('uploadType', $scope.data.uploadType);
                form.append('filePath', $scope.data.filePath);
                var request = new XMLHttpRequest();
                request.open("POST", $scope.data.url);
                request.setRequestHeader("Authorization", $scope.data.Authorization);
                request.send(form);
                //上传之后返回路径，进行入库保存
                request.onreadystatechange = function() {
                    if (request.status == '200' && request.readyState == 4) {
                        $scope.Module.User.FocusedRecord.Image = eval("(" + request.responseText + ")").path;
                        $scope.Module.User.save();
                    } else if (request.status == '400' || request.status == '404') {
                        BaseFunction.tip('保存失败', '图片上传失败');
                    }
                };
            }
        }

        $scope.btnCancel = function() {
            $scope.Module.User.cancel($scope.loadRoles);
        };
        $scope.btnAdd = function() {
            $scope.Module.User.add();
            $scope.data.myCroppedImage = 'users/img/default.png';
            $scope.myImage = '';
            $scope.loadRoles();
        };
        $scope.btnDelete = function() {
            $scope.Module.User.delete();
        };
        $scope.btnList = function() {
            $location.url('/index/User/List');
        };
        $scope.btnFindChange = function() {
            $scope.loadRoles();
        };
        $scope.roleRefBeforeShow = function(refScope) {
            var roleIds = [];
            for (var i = 0; i < $scope.Module._Role.Records.length; i++) {
                if ($scope.Module._Role.Records[i].Role !== undefined && $scope.Module._Role.Records[i].Role !== null) {
                    roleIds.push($scope.Module._Role.Records[i].Role._id);
                }
            }
            refScope.Module.Condition = {
                _id: {
                    $nin: roleIds
                }
            };
        };

        $scope.openAvatar = function() {
            myModal.$promise.then(myModal.show);
        };
        $scope.$on('modal.show', function() {
            if ($scope.myImage == '') {
                if ($scope.Module.User.FocusedRecord.Image) {
                    $scope.data.myCroppedImage = $scope.Module.User.FocusedRecord.Image;
                } else {
                    $scope.data.myCroppedImage = 'users/img/default.png';
                }
            }
            var handleFileSelect = function(evt) {
                var file = evt.currentTarget.files[0];
                var reader = new FileReader();
                reader.onload = function(evt) {
                    $scope.$apply(function($scope) {
                        var uri = evt.target.result;
                        var imgType = 'image/png';
                        if ('jpeg' == uri.substring(11, 15)) {
                            imgType = 'image/jpeg';
                        }
                        ImageCompress._createImage(uri, {
                            type: imgType
                        }).then(function(data) {
                            $scope.myImage = data;
                        });
                    });
                };
                reader.readAsDataURL(file);
            };
            angular.element(document.querySelector('#file')).on('change', handleFileSelect);
        });

        //将base64转成Blob
        function convertBase64UrlToBlob(urlData) {
            var bytes = window.atob(urlData.split(',')[1]);
            //去掉url的头，并转换为byte
            //处理异常,将ascii码小于0的转换为大于0
            var ab = new ArrayBuffer(bytes.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i);
            }

            return new Blob([ab], { type: 'image/png' });
        }

        function uploadImage() {
            var form = new FormData();
            form.append('file', convertBase64UrlToBlob($scope.data.myCroppedImage));
            form.append('uploadType', $scope.data.uploadType);
            form.append('filePath', $scope.data.filePath);
            var request = new XMLHttpRequest();
            request.open("POST", $scope.data.url);
            request.setRequestHeader("Authorization", $scope.data.Authorization);
            request.send(form);
            request.onreadystatechange = function() {
                if (request.status == '200' && request.readyState == 4) {
                    $scope.Module.User.FocusedRecord.Image = eval("(" + request.responseText + ")").path;
                    //执行save方法
                    $scope.Module.User.save(function() {
                        updateWebAfterSave();
                    });
                } else if (request.status == '400' || request.status == '404') {
                    BaseFunction.tip('保存失败', '图片上传失败');
                }

            };

        }

        function updateWebAfterSave() {
            User.queryMe().then(function() {
                $rootScope.$broadcast('profileChange');
            });
        }

        $scope.uploadAvatar = function() {
            //临时显示图片
            $scope.Module.User.FocusedRecord.Image = $scope.data.myCroppedImage;

            myModal.$promise.then(myModal.hide);
        };

        $scope.selectPhoto = function() {
            var ie = navigator.appName == "Microsoft Internet Explorer" ? true : false;
            if (ie) {
                document.getElementById("file").click();
            } else {
                var a = document.createEvent("MouseEvents");
                a.initEvent("click", true, true);
                document.getElementById("file").dispatchEvent(a);
            }
        };

        $scope.loadRoles = function() {
            $scope.Module._Role.Records = [];
            if ($scope.Module.User.FocusedRecord.Roles !== undefined && $scope.Module.User.FocusedRecord.Roles !== null) {
                for(var i=0; i<$scope.Module.User.FocusedRecord.Roles.length; i++){
                    var newRecord = $scope.Module._Role.add();
                    newRecord.Role = $scope.Module.User.FocusedRecord.Roles[i];
                }
            }

            $scope.Module._Role.emitOnLoadEvent();
        };

        //初始化
        BaseModule.initModule($scope, 'User');
        $scope.Module.User.Populate = {path: 'Roles'};
        $scope.Module.User.AfterOnAdd = function(record){
            record.IsEffective = true;
        };

        BaseModule.initModule($scope, 'Role');
        $scope.Module.Role.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;

        BaseModule.initModule($scope, '_Role');
        $scope.Module._Role.PageSize = 10;
        $scope.Module._Role.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;

        if ($stateParams.id) {
            $scope.Module.User.findById($stateParams.id, function(record) {
                $scope.Module.User.FocusedRecord = record;
                $scope.loadRoles();
            });
        } else {
            $scope.btnAdd();
        }
    }
]);
